// pages/index/login/index.js
const app = getApp(); // 获取应用实例

Page({

  /**
   * 页面的初始数据
   */
  data: {
		h5code: '', //网页登录CODE
		userInfo: {}, //微信信息
		wxnick: '', //微信昵称
        wxhead: '', //微信头像
        wxcode: '', //微信CODE
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
		// this.clip();
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {

	},
	
	// 登录码
	clip: function () {
		var that = this;
		wx.getClipboardData({
			success (res) {
				console.log(res);
				if (res.errMsg == 'getClipboardData:ok') {
					that.setData({
						h5code: res.data,
					});
				}
			}
		});
	},

	// 微信授权
	uinfo: function(){
		// 获取用户信息
		wx.getUserProfile({
      desc: '用于完善会员资料',
      success: (res) => {
        console.log(res);
        this.setData({
          userInfo: res.userInfo,
          wxnick: res.userInfo.nickName,
          wxhead: res.userInfo.avatarUrl,
        });
        wx.login({
            success: (res) => {
            console.log(res);
            this.setData({
                wxcode: res.code,
            });
            this.wxsave();
          },
        })
      },
      fail: (res) => {
        console.log('error');
      }
    });
	},

	// 保存信息
	wxsave: function () {
    // console.log(this.data); return
    var h5code = this.data.h5code;
		var formData = {
			h5code: h5code,
			userInfo: this.data.userInfo,
			nickName: this.data.wxnick,
      avatarUrl: this.data.wxhead,
      wxcode: this.data.wxcode,
		};
    wx.request({
      method: 'POST',
      url: app.globalData.domainXcx + '/user/auth',
      data: formData,
      timeout: 10000, //接口超时10S
      success: function (res) {
        res = res.data;
        console.log(res);
        if (res.code < 0) {
        wx.showToast({
          title: res.msg, icon: 'none'
        }); return
        }
        var uinfo = {
          uid: res.data.uid,
          nickName: res.data.nickName,
          avatarUrl: res.data.avatarUrl,
          h5code: h5code,
          phone: res.data.phone,
        };
        console.log(uinfo);
        wx.setStorageSync('userInfo', uinfo);
        wx.reLaunch({
          url: '/pages/index/index',
        }); return
      },
      fail: function () {
        console.log('error');
      }
    });
	},
})